#!/usr/bin/lua
package.cpath = "?;./?.so;/usr/lib/lua/5.1/?.so" 
package.path = "?;./?.lua;/usr/local/share/lua/5.1/iw/?.lua;/usr/lib/webif/LUA/?.lua;/usr/lib/webif/LUA/pkgs/?.lua;/usr/lib/lua/5.1/?.lua" 

require("common")
require("iw-luaipkg")

function tcount(t)
  local c = 0
  for i,k in pairs(t) do
    c = c + 1
  end
  return c
end

function repo_list(t)
  for i,v in pairsByKeys(t) do
    print(i,v.url)
  end
end

function list_installed_pkgs(pkg,detailled)
  if detailled == true then
    print(pkg:detailled_status())
  else
    for i,v in pairsByKeys(pkg.__installed) do
      print(i,v.Version)
    end
  end
end

function list_pkgs(t,detailled,notinstalled)
  for p,r in pairsByKeys(t.__repo) do
    local show = false
    for pkg, data in pairsByKeys(r.pkgs) do
      if notinstalled == true and t.__installed[pkg] == nil 
      or notinstalled == nil or notinstalled == false then
        if show == false then
          print(p,r.url)
          show = true
        end  
        if detailled then
          print("","Package",data.Package)
          for u,w in pairsByKeys(data) do
            if u ~= "Package" then
              print("","",u,w)
            end
          end
          print("")
        else
          print("",pkg,data.Version,data.Description)
--          print("",pkg,data.Version,data.MD5Sum)
        end
      end
    end
    if show == true then print("") end
  end
end

function list_toinstall(pkg)
  local tinstall = pkg:autoinstall_pkgs()
  for i = 1, #tinstall do
--    print(tinstall[i].url..tinstall[i].file,tinstall[i].MD5Sum)
    print(tinstall[i].Package,tinstall[i].Version,tinstall[i].Repository)
  end
end

function install_pkgs(pkg)
  local tinstall = pkg:autoinstall_pkgs()
  print("Please wait... ")
  for i = 1, #tinstall do
    local tmpdir = os.time()
    local dest = tinstall[i].Package.." ("..tinstall[i].Version..")"
    print("Installing "..dest)
    print("Downloading "..tinstall[i].url..tinstall[i].file)
    pkg:download(tinstall[i].url,tinstall[i].file,tmpdir)

    print("Unpack file "..tinstall[i].file)
--    local tfiles, tctrl_file, warning_exists, str_exec, tprovider_conf = pkg:unpack(tinstall[i],tmpdir)
    local tfiles, tctrl_file, str_exec = pkg:unpack(tinstall[i],tmpdir)

    tfiles, conffiles = pkg:wath_we_do(tfiles,tmpdir)

    print("Configuring "..dest)
    if string.len(str_exec) > 0 then
      print("Executing "..str_exec)
      local error = os.execute(str_exec)
      if error ~= 0 then
        print("Error while executing "..str_exec)
        print("Error Number : "..error)
      end
    end
    print("Copying files")
    pkg:processFiles(tfiles,tmpdir)
    local str_installed = "Package: "..tctrl_file.Package.."\n"
    str_installed = str_installed.."Version: "..tctrl_file.Version.."\n"
    if tctrl_file.Depends ~= nil then
      str_installed = str_installed.."Depends: "..tctrl_file.Depends.."\n"
    end
    str_installed = str_installed.."Provides: "..tctrl_file.Provides.."\n"
    str_installed = str_installed.."Root: /\n"
    str_installed = str_installed.."Status: install ok installed\n"
    str_installed = str_installed.."Architecture: "..tctrl_file.Architecture.."\n"
    if tctrl_file.Depends ~= nil then
      str_installed = str_installed.."Depends: "..tctrl_file.Depends.."\n"
    end
    if conffiles ~= nil then
      str_installed = str_installed.."Conffiles: "..conffiles.."\n"
    end
    str_installed = str_installed.."Installed-Time: "..tostring(os.time()).."\n"
    pkg:process_pkgs_file_new(str_installed)
    pkg:write_status(tmpdir)
    pkg:execute(tinstall[i].Package,".postinst")
  end
end

function remove_pkgs(pkg,recursive)
--  if conf_files == "keep" then keep_changed = true
--  elseif conf_files == "del" then del_changed = true
--  end
  pkg:remove_make_list()
  local ask, msg = pkg:remove_check_child(recursive)
  if ask == true then
    repeat
      print("iw-luapkg will be remove this packages")
      io.write(msg) 
      rspta = io.read()
      if rspta == "" then 
        rspta = "N"
      end
      rspta = string.upper(rspta)
      if rspta == "N" then
        print("\nNothing to do\nDone.")
        os.exit(0)
      end
    until rspta == "N" or rspta == "Y"
  end
  for i=1, #pkg.__toremove do
    tfilelist = pkg:remove_pkgs(pkg.__toremove[i])
    if del_changed == true and keep_changed == true then
      del_changed, keep_changed = nil, nil
    end
    if del_changed == true then
      for i,v in pairs(tfilelist) do
        tfilelist[i] = false
      end
    end
    if keep_changed ~= true then
      tfilelist = keep_changed_conf(tfilelist)
    end
    local rslt = pkg:execute(pkg.__toremove[i],".prerm")
    print("Removing "..pkg.__toremove[i])
    for i, v in pairs(tfilelist) do
      if v == false then
        os.execute("rm "..i.." 2>/dev/null")
--        print("rm "..i,v)
--        print("rm "..i)
      end
    end    
    rslt = pkg:execute(pkg.__toremove[i],".postrm")
    pkg:remove_done(pkg.__toremove[i])
  end
end

--[[
    
    print("Processing file list")
    print("Removing files "..infodir..self.__toremove[i].."*")
  end
end
]]--

function keep_changed_conf(tfilelist)
  for i,v in pairsByKeys(tfilelist) do
    if v == true then 
      repeat
        print(i.." was chaged")
        print("   Do you want remove this file?")
        io.write("   (Y/N) [default=N]? ")
        rspta = io.read()
        if rspta == "" then 
          rspta = "N"
        end
        rspta = string.upper(rspta)
        if rspta == "Y" then
          tfilelist[i] = false
        end
      until rspta == "N" or rspta == "Y"
    end
  end
  return tfilelist      
end

local script = arg[0]
local cmd = arg[1]
local pkg_list = ""
local detailled = false
local not_found = {}
local invalid_repo = {}

for i=2, #arg do
    if arg[i] == "-r" then
      use_repo = arg[i+1]
      i = i + 2
    elseif arg[i] == "-v" then
      use_version = arg[i+1]
      i = i + 2
    elseif arg[i] == "-notinstalled" then
      not_installed = true
    elseif arg[i] == "-d" then
      detailled = true
    elseif arg[i] == "-recursive" then
      recursive = true
    elseif arg[i] == "-keep_changed" then
      keep_changed = true
    elseif arg[i] == "-del_changed" then
      del_changed = true
--    elseif arg[i] == ">"
--    or arg[i] == ">>" then
--      break
    else 
      pkg_list=pkg_list.." "..arg[i]
    end
    if i>=#arg then break end
end
pkg_list = string.trim(pkg_list)
if pkg_list == nil then pkg_list = "" end

if cmd == "list" then
  print("List of Packages "..type(pkg_list),pkg_list)
  local pkg = lpkgClass.new(pkg_list,use_repo)
	pkg:loadRepo_list(pkg.repo_list)
  
  list_pkgs(pkg,detailled,not_installed)
  not_found = pkg.__notfound
  invalid_repo = pkg.__invalidrepo

elseif cmd == "list_installed" then
  print("List Installed packages")
  local pkg = lpkgClass.new(pkg_list,use_repo)
  list_installed_pkgs(pkg,detailled)
  not_found = pkg.__notfound
  invalid_repo = pkg.__invalidrepo

elseif cmd == "list_repo" then
  print("Repository List")
  local pkg = lpkgClass.new(pkg_list,use_repo)
  repo_list(pkg.__repo)
  not_found = pkg.__notfound
  invalid_repo = pkg.__invalidrepo

elseif cmd == "check" then
  if string.len(pkg_list) > 0 then
    print("To install packages")
    local pkg = lpkgClass.new(pkg_list,use_repo)
  	pkg:loadRepo_list(pkg.repo_list)
    list_toinstall(pkg,use_version)
    not_found = pkg.__notfound
    invalid_repo = pkg.__invalidrepo
  else
    print([[Package(s) must be especificated]])
  end

elseif cmd == "install" then
  if string.len(pkg_list) > 0 then
    print("install packages")
    local pkg = lpkgClass.new(pkg_list,use_repo)
  	pkg:loadRepo_list(pkg.repo_list)
    install_pkgs(pkg,use_version)
    not_found = pkg.__notfound
    invalid_repo = pkg.__invalidrepo
  else
    print([[Package(s) must be especificated]])
  end

elseif cmd == "update" then
    print("Updating packages list")
    local pkg = lpkgClass.new()
  	pkg:update()
    invalid_repo = pkg.__invalidrepo

elseif cmd == "remove" then
  if string.len(pkg_list) > 0 then
--    print("Removing packages")
--    if del_changed == true then conf_files = "del" end
--    if keep_changed == true then conf_files = "keep" end
--    if keep_changed == true and del_changed == true then conf_files = nil end
    local pkg = lpkgClass.new(pkg_list)
    remove_pkgs(pkg,recursive,conf_files)
    not_found = pkg.__notfound
    invalid_repo = pkg.__invalidrepo
  else
    print([[Package(s) must be especificated]])
  end

else
  print(arg[0].." [command] [package[*]] [-options]")
  print("","commands")
  print("","","list                  ", "list of packages")
  print("","","list_installed        ", "list installed packages")
  print("","","list_repo             ", "list repositories")
  print("","","check                 ", "return list of files to be install")
  print("","","install               ", "install packages")
  print("","","update                ", "update list of packages")
  print("","","remove                ", "update list of packages")
  print("","package")
  print("","","packagename ...       ", "list of packages (space separated)")
  print("","","packagename* ...      ", "search all packages start with")
  print("","","                      ", "packagename ")
  print("","options")
  print("","","-r repository_name,...", "use only repositories in this list ")
  print("","","                      ", "(comma separated)")
  print("","","-d                    ", "Detailled list")
  print("","","-notinstalled         ", "list packages not installed")
  print("","","-recursive            ", "Allow ipkg to remove package and all")
  print("","","                      ", "that depend on it.")
  print("","","-keep_changed         ", "Keep files controled in conffiles when")
  print("","","                      ", "they was changed.")
  print("","","-del_changed          ", "Delete all files controled in conffiles")
  print("How it work")
  print("  install or check")
  print("    luapkg install foo*")
  print("      Read all repositories and select all packages that name start with foo and")
  print("      hight Version of each one and install they")
  print("")
  print("    luapkg install foo* -r reponame")
  print("      Install all packages that name start with foo from repository 'reponame'")
  print("")
  print("    luapkg install foo bar*")
  print("      Read all repositories install foo from repository with hight Version of")
  print("      foo and install all packages that name start with bar from repository ")
  print("      with hight Version")
  print("")
  print("    luapkg install foo bar* -r reponame")
  print("      Install foo and all packages that name start with bar from repository")
  print("      'reponame'")
end
local show = false
for i,v in pairsByKeys(not_found) do
  if show == false then
    print("NOT FOUND!!!", "Not repository for this packages...")
    show = true 
  end
  print("",i)
end
show = false
if #invalid_repo > 0 then
  for i=1, #invalid_repo do
    if show == false then
      print("Invalid repo")
      show = true 
    end
    print("",invalid_repo[i])
  end
end
